package com.lovezy.platform.discuz.datasource;

import com.lovezy.platform.core.mybatis.MapperHelper;
import com.lovezy.platform.discuz.mapper.DiscuzMemberMapper;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by jin on 2017/11/3.
 */
@Configuration
public class DiscuzDatasourceConfiguration {

    @Bean
    public DiscuzDataSource discuzDataSource(DiscuzDataProperties properties) throws Exception{
        DiscuzDataSource dataSource = new DiscuzDataSource();
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(properties.getDriverClassName());
        ds.setUrl(properties.getUrl());
        ds.setUsername(properties.getUsername());
        ds.setPassword(properties.getPassword());

        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("discuz", transactionFactory, ds);
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration(environment);
        configuration.addMapper(DiscuzMemberMapper.class);
        SqlSessionFactory factory = new DefaultSqlSessionFactory(configuration);
        dataSource.setDataSource(ds);
        dataSource.setSqlSessionFactory(factory);
        return dataSource;
    }

    @Bean("discuzMapperHelper")
    public MapperHelper mapperHelper(DiscuzDataSource dataSource) {
        return new MapperHelper(dataSource.getSqlSessionFactory());
    }

}
